//
//  ComposeViewController.swift
//  sina
//
//  Created by DXapple on 15/11/21.
//  Copyright © 2015年 sqlite. All rights reserved.
//

import UIKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    @objc private func selectPicture() {
       
    selectorVC.view.snp_updateConstraints { (make) -> Void in
        make.height.equalTo(224 + 120)
        }
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)

    }
    
    
    @objc private func send() {
    
        let urlString = "2/statuses/update.json"
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus(AppErrorTip)
            return
        }
        let parmaters = ["access_token" : token,"status": textView.text]
       
       NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parmaters) { (result, error) -> () in
        if error != nil {
            SVProgressHUD.showErrorWithStatus(AppErrorTip)
            return
        }
        SVProgressHUD.showSuccessWithStatus("发布微博成功")
        self.dismissViewControllerAnimated(true, completion: nil)
        print(result)
        
        }
        
        
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }

    private func setupUI() {
        setNavBar()
        setupTextView()
        setupToolBar()
        registerNofication()
        setSelectorView()
        
    }
    private func setSelectorView() {
        //添加子视图控制器
        addChildViewController(selectorVC)
        //添加视图
        view.addSubview(selectorVC.view)
        
        //调整视图层次结构
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    
    }
    
    
    private func registerNofication() {
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
    }
    deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    @objc private func keyboardWillChange(n: NSNotification) {
    
//        print(n)
        //获取动画事件
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //修改toolbar约束  获取键盘高度
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    private lazy var textView: UITextView = {
    
        let tv = UITextView()
        tv.delegate = self
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.alwaysBounceVertical = true
        return tv
        
    }()
    private lazy var
    placeHolderLabel: UILabel = UILabel(title: "分享新鲜事......", size: 18, color: UIColor.lightGrayColor())

    private lazy var
    toolBar: UIToolbar = UIToolbar()
    private lazy var
    selectorVC: PictureSelectorViewController = PictureSelectorViewController()
  
}
extension ComposeViewController: UITextViewDelegate {

    func textViewDidChangeSelection(textView: UITextView) {
        //设置站位文本隐身
        placeHolderLabel.hidden = textView.hasText()
        //设置发布按钮的交互
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        
    }

}



extension ComposeViewController{
    private func setupTextView() {
        view.addSubview(textView)
        textView.backgroundColor = UIColor.randomColor()
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.height / 3 )
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
        
    }
    
    private func setupToolBar() {
        
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(view)
            make.height.equalTo(40)
        }
        
        //设置toobar按钮以及点击事件
        var items = [UIBarButtonItem]()
        //添加uibarbuttontiem
         let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_add_background"]]
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])

            items.append(item)
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
            
        }
        
        items.removeLast()
        
      toolBar.items = items
        
    }
    //设置toolbar 以及事件
    
    
    
    
    private func  setNavBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")

        self.navigationItem.rightBarButtonItem?.enabled = false
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        //添加导航栏发布信息的uilabel
        let titleLabel = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.lightGrayColor())
        
        //添加子视图
        titleView.addSubview(titleLabel)
        titleLabel.addSubview(nameLabel)
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        
    }
    

}



